<template>
  <div class="px-4 sm:px-8 md:px-16 lg:px-48 pt-4 w-full">
    <div class="flex flex-col">
      <n-card :title="'干部管理'">
        <template #header-extra>
          <div class="flex items-center">
            <n-button type="primary" @click="openCreateModal" class="px-6 mr-4">
              新增干部信息
            </n-button>
            <n-button type="info" @click="openImportModal" class="px-6 mr-4">
              批量导入
            </n-button>
            <n-button type="success" @click="handleExport" :loading="isExporting" class="px-6">
              导出至Excel
            </n-button>
          </div>
        </template>

        <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-top: 16px; margin-bottom: 4px; align-items: center;">
          <div style="flex-shrink: 0; width: 280px;">
            <n-input v-model:value="searchTerm" placeholder="按姓名、单位搜索..." clearable @input="handleSearchDebounced"
              @clear="handleSearchDebounced">
              <template #prefix>
                <n-icon :component="SearchOutline" />
              </template>
            </n-input>
          </div>
          <div style="flex-shrink: 0; width: 180px;">
            <n-select v-model:value="filterLevel" placeholder="选择级别" :options="levelFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex-shrink: 0; width: 200px;">
            <n-select v-model:value="filterCadreType" placeholder="选择干部类型" :options="cadreTypeFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex: 1;" />
        </div>

        <div style="margin-top: 0;">
          <n-data-table
            ref="dataTableInstRef"
            :columns="columns"
            :data="cadreStore.allCadres"
            :loading="cadreStore.loading || unitStore.isLoading || universityStore.isLoading"
            :pagination="paginationConfig"
            remote
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
            @update:sorter="handleSorterChange"
            class="min-w-full"
            :scroll-x="3200"
          />
        </div>
      </n-card>
    </div>
  </div>

  <n-modal v-model:show="showModal" preset="card" :style="{ width: '800px' }" :title="modalTitle" size="huge"
    :bordered="false" :segmented="{ content: 'soft', footer: 'soft' }" closable @after-leave="handleModalClose">
    <cadre-form ref="cadreFormRef" :initial-data="editingCadre" @submit="handleFormSubmit" @cancel="closeModal" />
  </n-modal>

  <n-modal
    v-model:show="showPlanModal"
    preset="card"
    :style="{ width: '900px' }"
    :title="planModalTitle"
    size="huge"
    :bordered="false"
    :segmented="{ content: 'soft', footer: 'soft' }"
    closable
    @after-leave="handlePlanModalClose"
  >
    <plan-form
      ref="planFormRef"
      :initial-data="planInitialData"
      :fixed-cadre="true"
      @submit="handlePlanFormSubmit"
      @cancel="closePlanModal"
    />
  </n-modal>

  <!-- 导入对话框 -->
  <CadreImportDialog
    v-model:show="showImportModal"
    @success="handleImportSuccess"
  />
</template>

<script setup>
import { SearchOutline } from "@vicons/ionicons5";
import { h, ref, onMounted, watch, computed } from "vue";
import {
  NIcon,
  NDataTable,
  NButton,
  useMessage,
  NInput,
  NSelect,
  NModal,
  NEllipsis,
  NCard,
  useDialog,
} from "naive-ui";
import CadreForm from '@/components/CadreForm.vue';
import PlanForm from '@/components/PlanForm.vue';
import CadreImportDialog from '@/components/CadreImportDialog.vue';

import { useCadreStore } from '@/stores/cadreStore';
import { useUnitStore } from '@/stores/unitStore';
import { useUniversityStore } from '@/stores/universityStore';
import { usePlanStore } from '@/stores/planStore';

const message = useMessage();
const dialog = useDialog();
const cadreStore = useCadreStore();
const unitStore = useUnitStore();
const universityStore = useUniversityStore();
const planStore = usePlanStore();

const dataTableInstRef = ref(null);

// --- Modal control for CadreForm ---
const showModal = ref(false);
const modalTitle = ref('新增干部信息');
const editingCadre = ref(null);
const cadreFormRef = ref(null);

// --- Modal control for PlanForm ---
const showPlanModal = ref(false);
const planModalTitle = ref('为干部排课');
const currentSchedulingCadre = ref(null);
const planInitialData = ref(null);
const planFormRef = ref(null);

// --- Modal control for Import ---
const showImportModal = ref(false);

const openCreateModal = () => {
  editingCadre.value = null;
  modalTitle.value = '新增干部信息';
  showModal.value = true;
};

const openImportModal = () => {
  showImportModal.value = true;
};

const handleImportSuccess = async () => {
  // 导入成功后刷新数据
  await fetchCadresWithFilters();
};

const openEditModal = (rowData) => {
  // 处理后端返回的populated数据，将对象转换为ID
  const processedData = { ...rowData };

  // 处理unitId
  if (processedData.unitId && typeof processedData.unitId === 'object') {
    processedData.unitId = processedData.unitId._id;
  }

  // 处理意向授课高校
  if (processedData.intendedUniversity1 && typeof processedData.intendedUniversity1 === 'object') {
    processedData.intendedUniversity1 = processedData.intendedUniversity1._id;
  }
  if (processedData.intendedUniversity2 && typeof processedData.intendedUniversity2 === 'object') {
    processedData.intendedUniversity2 = processedData.intendedUniversity2._id;
  }
  if (processedData.intendedUniversity3 && typeof processedData.intendedUniversity3 === 'object') {
    processedData.intendedUniversity3 = processedData.intendedUniversity3._id;
  }

  console.log('编辑数据处理前:', rowData);
  console.log('编辑数据处理后:', processedData);

  editingCadre.value = processedData;
  modalTitle.value = '编辑干部信息';
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
};

const handleModalClose = () => {
  if (cadreFormRef.value && typeof cadreFormRef.value.resetForm === 'function') {
    cadreFormRef.value.resetForm();
  }
  editingCadre.value = null;
};

const handleFormSubmit = async (formData) => {
  // 立即关闭对话框，提升用户体验
  closeModal();

  try {
    if (editingCadre.value && editingCadre.value._id) {
      await cadreStore.updateCadre(editingCadre.value._id, formData);
      message.success('干部信息更新成功');
    } else {
      await cadreStore.addCadre(formData);
      message.success('干部信息新增成功');
    }

    // 重新获取当前页数据
    await fetchCadresWithFilters();
  } catch (error) {
    console.error("表单提交失败:", error);
    message.error(editingCadre.value ? '更新失败，请重试' : '新增失败，请重试');
    // 不需要重新抛出错误，因为对话框已经关闭了
  }
};

// --- Functions for Plan Modal ---
const openScheduleModal = (cadre) => {
  console.log('开始为干部排课:', cadre);
  currentSchedulingCadre.value = { _id: cadre._id, name: cadre.name };
  planModalTitle.value = `为 ${cadre.name} 排课`;
  planInitialData.value = {
    cadreId: String(cadre._id), // 确保ID是字符串格式
    cadreName: cadre.name,
  };
  showPlanModal.value = true;
};

const closePlanModal = () => {
  showPlanModal.value = false;
};

const handlePlanModalClose = () => {
  if (planFormRef.value && typeof planFormRef.value.resetForm === 'function') {
    planFormRef.value.resetForm();
  }
  currentSchedulingCadre.value = null;
  planInitialData.value = null;
};

const handlePlanFormSubmit = async (formDataFromPlanForm) => {
  console.log('收到的排课表单数据:', formDataFromPlanForm);
  const cadreNameForMessage = currentSchedulingCadre.value?.name || '该干部';

  // 立即关闭对话框，提升用户体验
  closePlanModal();

  try {
    await planStore.addPlan(formDataFromPlanForm);
    message.success(`为干部 ${cadreNameForMessage} 新增授课计划成功`);
  } catch(error) {
    console.error("排课提交失败:", error);
    console.error("错误详情:", error.response?.data);

    // 显示更详细的错误信息
    const errorMessage = error.response?.data?.message || error.response?.data?.error || '排课失败，请重试';
    message.error(`创建授课计划失败: ${errorMessage}`);
    // 不需要重新抛出错误，因为对话框已经关闭了
  }
};

// --- Table Column Definitions (Maps and Helper) ---
const genderMap = { male: '男', female: '女', other: '其他', '男': '男', '女': '女' };
const levelMap = {
  provincial: '省级',
  departmental: '厅局级',
  county: '县处级',
  township: '乡科级',
  other_level: '其他',
  '省级': '省级',
  '厅局级': '厅局级',
  '县处级': '县处级',
  '乡科级': '乡科级'
};
const cadreTypeMap = {
  '厅局级干部': '厅局级干部',
  '中管干部': '中管干部'
};
const educationMap = {
  doctorate: '博士研究生',
  master: '硕士研究生',
  bachelor: '本科',
  associate: '大专',
  high_school: '高中',
  other_education: '其他',
  '博士研究生': '博士研究生',
  '硕士研究生': '硕士研究生',
  '本科': '本科',
  '大专': '大专'
};
const degreeMap = {
  phd: '博士',
  master_degree: '硕士',
  bachelor_degree: '学士',
  none: '无',
  '博士': '博士',
  '硕士': '硕士',
  '学士': '学士'
};

// Options for filters
const levelFilterOptions = ref([
  { label: '省级', value: '省级' },
  { label: '厅局级', value: '厅局级' },
  { label: '县处级', value: '县处级' },
  { label: '乡科级', value: '乡科级' }
]);
const cadreTypeFilterOptions = ref([
  { label: '厅局级干部', value: '厅局级干部' },
  { label: '中管干部', value: '中管干部' }
]);



// --- Data Mapping for Display ---
const unitNameMap = computed(() => {
  const map = {};
  // 优先使用 unitOptions，如果没有则使用 allUnits
  const units = unitStore.unitOptions.length > 0 ? unitStore.unitOptions : unitStore.allUnits;
  units.forEach(unit => {
    map[unit._id || unit.id] = unit.name;
  });
  return map;
});

const universityNameMap = computed(() => {
  const map = {};
  // 优先使用 universityOptions，如果没有则使用 allUniversities
  const universities = universityStore.universityOptions.length > 0 ? universityStore.universityOptions : universityStore.allUniversities;
  universities.forEach(uni => {
    map[uni._id || uni.id] = uni.schoolName;
  });
  return map;
});

const getDisplayValue = (value, map, defaultValue = '未知') => map[value] || value || defaultValue;

const statusOptions = [
  { label: '在职', value: 'active' },
  { label: '借调', value: 'seconded' },
];
const statusDisplayMap = Object.fromEntries(statusOptions.map(opt => [opt.value, opt.label]));

const createColumns = ({ onEdit, onSchedule, onDelete }) => {
  return [
    {
      title: '序号',
      key: 'tableId',
      width: 60,
      fixed: 'left',
      render: (_, index) => (paginationConfig.value.page - 1) * paginationConfig.value.pageSize + index + 1
    },
    { title: '姓名', key: 'name', width: 100, sorter: true, fixed: 'left', ellipsis: { tooltip: true } },
    {
      title: '性别', key: 'gender', width: 70,
      render: (row) => getDisplayValue(row.gender, genderMap)
    },
    {
      title: '出生年月', key: 'birthDate', width: 120, sorter: true,
      render: (row) => row.birthDate ? new Date(row.birthDate).toLocaleDateString() : 'N/A'
    },
    { title: '籍贯', key: 'nativePlace', width: 100, ellipsis: { tooltip: true } },
    {
      title: '级别', key: 'level', width: 100, sorter: true,
      render: (row) => getDisplayValue(row.level, levelMap)
    },
    { title: '职务', key: 'position', width: 120, ellipsis: { tooltip: true } },
    {
      title: '干部类型', key: 'cadreType', width: 120,
      render: (row) => getDisplayValue(row.cadreType, cadreTypeMap)
    },
    {
      title: '单位归属',
      key: 'unitId',
      width: 180,
      sorter: true,
      render: (row) => {
        // 处理unitId可能是对象或字符串的情况
        let unitName = '未分配';
        if (row.unitId) {
          if (typeof row.unitId === 'object' && row.unitId.name) {
            // 如果unitId是对象，直接使用其name属性
            unitName = row.unitId.name;
          } else if (typeof row.unitId === 'string') {
            // 如果unitId是字符串，从映射中查找
            unitName = unitNameMap.value[row.unitId] || '未分配';
          }
        }
        return h(NEllipsis, { tooltip: { style: { maxWidth: '300px' }}}, { default: () => unitName });
      }
    },
    {
      title: '最高学历', key: 'highestEducation', width: 120,
      render: (row) => getDisplayValue(row.highestEducation, educationMap)
    },
    {
      title: '最高学位', key: 'highestDegree', width: 100,
      render: (row) => getDisplayValue(row.highestDegree, degreeMap)
    },
    {
      title: '熟悉专长', key: 'expertise', width: 180,
      render: row => h(NEllipsis, { tooltip: { style: { maxWidth: '300px' } } }, { default: () => row.expertise || 'N/A' })
    },
    {
      title: '意向授课高校1', key: 'intendedUniversity1', width: 180,
      render: row => {
        let universityName = 'N/A';
        if (row.intendedUniversity1) {
          if (typeof row.intendedUniversity1 === 'object' && row.intendedUniversity1.schoolName) {
            // 如果是对象，直接使用其schoolName属性
            universityName = row.intendedUniversity1.schoolName;
          } else if (typeof row.intendedUniversity1 === 'string') {
            // 如果是字符串，从映射中查找
            universityName = universityNameMap.value[row.intendedUniversity1] || 'N/A';
          }
        }
        return h(NEllipsis, { tooltip: {style: {maxWidth: '300px'}}}, { default: () => universityName });
      }
    },
    {
      title: '意向授课高校2', key: 'intendedUniversity2', width: 180,
      render: row => {
        let universityName = 'N/A';
        if (row.intendedUniversity2) {
          if (typeof row.intendedUniversity2 === 'object' && row.intendedUniversity2.schoolName) {
            // 如果是对象，直接使用其schoolName属性
            universityName = row.intendedUniversity2.schoolName;
          } else if (typeof row.intendedUniversity2 === 'string') {
            // 如果是字符串，从映射中查找
            universityName = universityNameMap.value[row.intendedUniversity2] || 'N/A';
          }
        }
        return h(NEllipsis, { tooltip: {style: {maxWidth: '300px'}}}, { default: () => universityName });
      }
    },
    {
      title: '意向授课高校3', key: 'intendedUniversity3', width: 180,
      render: row => {
        let universityName = 'N/A';
        if (row.intendedUniversity3) {
          if (typeof row.intendedUniversity3 === 'object' && row.intendedUniversity3.schoolName) {
            // 如果是对象，直接使用其schoolName属性
            universityName = row.intendedUniversity3.schoolName;
          } else if (typeof row.intendedUniversity3 === 'string') {
            // 如果是字符串，从映射中查找
            universityName = universityNameMap.value[row.intendedUniversity3] || 'N/A';
          }
        }
        return h(NEllipsis, { tooltip: {style: {maxWidth: '300px'}}}, { default: () => universityName });
      }
    },
    {
      title: '操作',
      key: 'actions',
      width: 250,
      fixed: 'right',
      render(row) {
        return h('div', { style: 'display: flex; align-items: center; justify-content: center;' }, [
          h(NButton, { size: 'small', type: 'primary', ghost: true, onClick: () => onEdit(row), style: 'margin-right: 8px;' }, { default: () => '编辑' }),
          h(NButton, {
            size: 'small',
            type: 'info',
            ghost: true,
            onClick: () => onSchedule(row),
            style: 'margin-right: 8px;'
          }, { default: () => '排课' }),
          h(NButton, { size: 'small', type: 'error', ghost: true, onClick: () => onDelete(row) }, { default: () => '删除' })
        ]);
      },
    },
  ];
};

const handleDelete = (rowData) => {
  dialog.warning({
    title: '确认删除',
    content: `您确定要删除干部 "${rowData.name}" 吗？此操作不可恢复。`,
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: () => {
      // 立即关闭对话框，异步执行删除操作
      performDelete(rowData);
      return true; // 立即关闭对话框
    }
  });
};

const performDelete = async (rowData) => {
  const loadingMessage = message.loading(`正在删除干部 ${rowData.name}...`, { duration: 0 });
  try {
    await cadreStore.deleteCadre(rowData._id);
    loadingMessage.destroy();
    message.success(`干部 ${rowData.name} 已删除`);
    // 重新获取当前页数据
    await fetchCadresWithFilters();
  } catch (error) {
    loadingMessage.destroy();
    message.error('删除失败，请重试');
    console.error("删除失败:", error);
  }
};

// 刷新干部列表数据
const refreshCadreList = async () => {
  try {
    // 重新获取当前页数据
    await fetchCadresWithFilters();
  } catch (error) {
    console.error("刷新干部列表失败:", error);
    message.error("刷新数据失败");
  }
};

const columns = ref(createColumns({
  onEdit: openEditModal,
  onSchedule: openScheduleModal,
  onDelete: handleDelete,
}));

// --- Data Fetching, Filtering, Pagination, Sorting ---
const searchTerm = ref('');
const filterLevel = ref([]);
const filterCadreType = ref([]);

const paginationConfig = computed(() => ({
  page: cadreStore.pagination.page,
  pageSize: cadreStore.pagination.limit,
  itemCount: cadreStore.pagination.total,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  showQuickJumper: true,
}));

const currentSortKey = ref(null);
const currentSortOrder = ref(false);
const isExporting = ref(false);



let searchDebounceTimer = null;
const handleSearchDebounced = () => {
    clearTimeout(searchDebounceTimer);
    searchDebounceTimer = setTimeout(() => {
        handleSearch();
    }, 300);
};

const handleSearch = async () => {
  await fetchCadresWithFilters({ page: 1 });
};

// 获取带过滤条件的干部数据
const fetchCadresWithFilters = async (paginationParams = {}) => {
  try {
    const params = {
      page: paginationParams.page || cadreStore.pagination.page,
      pageSize: paginationParams.pageSize || cadreStore.pagination.limit,
      search: searchTerm.value,
      level: filterLevel.value?.length > 0 ? filterLevel.value.join(',') : undefined,
      cadreType: filterCadreType.value?.length > 0 ? filterCadreType.value.join(',') : undefined,
      sortBy: currentSortKey.value,
      sortOrder: currentSortOrder.value === 'ascend' ? 'asc' : currentSortOrder.value === 'descend' ? 'desc' : undefined,
    };

    // 移除undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });

    await cadreStore.fetchCadres(params);
  } catch (error) {
    console.error('获取干部数据失败:', error);
    message.error('获取数据失败');
  }
};

const applyTableFilters = async () => {
  await fetchCadresWithFilters({ page: 1 });
};



const handlePageChange = async (page) => {
  await fetchCadresWithFilters({ page });
};

const handlePageSizeChange = async (pageSize) => {
  await fetchCadresWithFilters({ page: 1, pageSize });
};

const handleSorterChange = async (sorter) => {
  if (sorter && sorter.columnKey && sorter.order) {
    currentSortKey.value = sorter.columnKey;
    currentSortOrder.value = sorter.order;
  } else {
    currentSortKey.value = null;
    currentSortOrder.value = false;
  }
  await fetchCadresWithFilters({ page: 1 });
};

// 导出功能
const handleExport = async () => {
  if (isExporting.value) return;

  try {
    isExporting.value = true;

    // 使用简单的 window.open 方式
    const exportUrl = 'http://localhost:3001/api/export/cadres';
    window.open(exportUrl, '_blank');

    message.success('干部信息导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败，请重试');
  } finally {
    isExporting.value = false;
  }
};

onMounted(async () => {
  try {
    await Promise.all([
      // 同时加载选项数据
      unitStore.fetchUnits(),
      unitStore.fetchUnitOptions(),
      universityStore.fetchUniversities(),
      universityStore.fetchUniversityOptions()
    ]);
    // 加载第一页干部数据
    await fetchCadresWithFilters();
  } catch (error) {
    console.error("Error during initial data fetch:", error);
    message.error("初始化数据加载失败");
  }
});
</script>